package com.stjb.furns.service.impl;

import com.stjb.furns.dao.BasicDAO;
import com.stjb.furns.dao.FurnDAO;
import com.stjb.furns.dao.OrderDAO;
import com.stjb.furns.dao.OrderItemDAO;
import com.stjb.furns.dao.impl.FurnDAOImpl;
import com.stjb.furns.dao.impl.OrderDAOImpl;
import com.stjb.furns.dao.impl.OrderItemDAOImpl;
import com.stjb.furns.entity.*;
import com.stjb.furns.service.OrderService;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

/**
 * @author situ
 * @version 1.0
 * @date 2025/5/29 21:53
 * @Description:
 */
public class OrderServiceImpl implements OrderService {

    private OrderDAO orderDAO = new OrderDAOImpl();
    private OrderItemDAO orderItemDAO = new OrderItemDAOImpl();
    private FurnDAO furnDAO = new FurnDAOImpl();


    /**
     * 保存购物车数据到数据库
     * @param cart
     * @param memberId
     * @return 返回订单号
     */
    @Override
    public String saveOrder(Cart cart, int memberId) {

        //生成uuid 为订单号 是唯一的 毫秒 ＋ 用户id
        String orderId = System.currentTimeMillis()+ "" + memberId;
        //格式化一个时间用于前端显示
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String formattedDate = sdf.format(date);
        Order order = new Order(orderId, date, cart.getTotalPrice(), 0, memberId,formattedDate);
        orderDAO.saveOrder(order);
        //通过cart对象 遍历CartItem 构建OrderItem对象 保存到数据库表 order_item
        HashMap<Integer, CartItem> items = cart.getItems();
        //遍历 构建orderItem 对象
        Set<Integer> keys = items.keySet();
        for (Integer id : keys) {
            CartItem item = items.get(id);
            OrderItem orderItem = new OrderItem(null, item.getName(), item.getPrice(),
                    item.getCount(), item.getTotalPrice(), orderId);
            //保存在数据库
            orderItemDAO.saveOrderItem(orderItem);

            //更新furn对象 销量sales增加 库存stock 减少
            //根据id得到对象
            Furn furn = furnDAO.queryFurnById(id);
            //更新销量
            furn.setSales(furn.getSales() + item.getCount());
            //更新库存
            furn.setStock(furn.getStock() - item.getCount());
            //更新到数据库 同步到数据库
            furnDAO.updateFurn(furn);
        }
        //清空购物车
        cart.clean();
        return orderId;
    }

    /**
     * 根据传入的id查订单信息
     * @param userId
     */
    @Override
    public List<Order> queryOrderByUserId(int userId) {
        return orderDAO.queryOrderByMemberId(userId);
    }
}
